from django.shortcuts import render
from dwebsocket.decorators import accept_websocket, require_websocket
from django.http import HttpResponse
import paramiko,json,time
import os
from random import randint
import uuid
#print uuid.uuid1()


def ssh_exec(ipaddr,port,user,password,tempfile,diskpath,xmlfile,xmlpath,cpu,mem,network,ip_min,ip_max,request):

    ssh = paramiko.SSHClient()
    tim = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime())
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect(hostname=ipaddr, port=port, username=user, password=password)
    except:
        request.websocket.send('链接服务器失败'+ ipaddr + '--&#10;')
    else:
        for ip in range(int(ip_min), int(ip_max)+1):
            mac = ":".join(["%02x" % x for x in map(lambda x: randint(0, 255), range(3))])
            uuidi = uuid.uuid1()
            name = network+'.'+str(ip)
            ipadd = network+'.'+str(ip)
            new_disk_path = diskpath+'/'+name+'.img'
            new_xml_name = xmlpath+'/'+name+'.xml'
            sftp = ssh.open_sftp()
            try:
                sftp.stat(new_disk_path)
                request.websocket.send(new_disk_path+'存在--&#10;')
                return '--&#10;'
            except IOError:
                pass

            try:
                sftp.stat(new_xml_name)
                request.websocket.send(new_xml_name+'存在--&#10;')
                return '--&#10;'
            except IOError:
                pass
            #stdin,stdout,stderr = ssh.exec_command('[ -f %s ] || echo 2' % new_disk_path, get_pty=True)
            #print('1111111',stdout.readline().strip(),'1111111')
            
            #if stdout.readline().strip() == '2':
            #    request.websocket.send(new_disk_path+'存在.--&#10;')
            #    return '--&#10;'
            #else:
            #    #pass
            #    request.websocket.send(new_disk_path+'不存在.开始克隆--&#10;')

            #stdin,stdout,stderr = ssh.exec_command('[ -f %s ] || echo 2' % new_xml_name, get_pty=True)
            #if stdout.readline().strip() == '2':
            #    request.websocket.send(new_xml_name+'存在.--&#10;')
            #    return '--&#10;'
            #else:
            #    pass
            #    #request.websocket.send(new_xml_name+'不存在.开始克隆--&#10;')       

            cmdlist = [
                'cp '+tempfile+' '+new_disk_path,
                'cp '+xmlfile+' '+new_xml_name,
                'sed -i \'s@<name>.*<@<name>\'%s\'<@g\' %s' % (name,new_xml_name),
                'sed -i \'s@<uuid>.*<@<uuid>\'%s\'<@g\' %s' % (str(uuidi),new_xml_name),
                'sed -i \"s@<source file=\'.*\'/>@<source file=\'%s\'/>@g\" %s' % (new_disk_path,new_xml_name),
                'sed -i \"s@<mac address=\'.*\'/>@<mac address=\'52:54:00:%s\'/>@g\" %s' % (mac,new_xml_name),
                'sed -i \"s@<vcpu placement=\'static\'>.*</vcpu>@<vcpu placement=\'static\'>%s</vcpu>@g\" %s' % (cpu,new_xml_name),
                'sed -i \"s@<memory unit=\'KiB\'>.*</memory>@<memory unit=\'KiB\'>%s</memory>@g\" %s' % (mem,new_xml_name),
                'sed -i \"s@<currentMemory unit=\'KiB\'>.*</currentMemory>@<currentMemory unit=\'KiB\'>%s</currentMemory>@g\" %s' % (mem,new_xml_name),
                'virt-customize -a %s --run-command \"sed -i \'s@IPADDR=.*@IPADDR=%s@g\' /etc/sysconfig/network-scripts/ifcfg-eth0\"' % (new_disk_path,name),
                'virsh define %s' % new_xml_name,
                'virsh start %s' % name
            ]
            print(diskpath+network+'.'+str(ip)+'.img')
            for cmd in cmdlist:
                request.websocket.send(cmd)
                stdin, stdout, stderr = ssh.exec_command(cmd , get_pty=True)
                while True:
                    nextline = stdout.readline().strip()
                    if not nextline:
                        request.websocket.send(nextline + '&#10;')
                        break
        ssh.close()
        return '----exec end--by:linuxsamu----'+ ipaddr + '--' + tim + '--&#10;'
    
@accept_websocket
def toolman(request):
    if not request.is_websocket():    #判断是不是websocket连接
        return render(request,'index.html')
    else:
        for message in request.websocket:
            #message = message.decode('utf-8')
            #print('111',message)
            jsondata = json.loads(message)
            #print('222',jsondata)            
            if '' in jsondata.values():
                request.websocket.send('send data has None,please check resend &#10;')
            else:
                ipaddr = jsondata['ipaddr'].strip()
                port = jsondata['port'].strip()
                user = jsondata['user'].strip()
                password = jsondata['password'].strip()
                tempfile = jsondata['tempfile'].strip()
                diskpath = jsondata['diskpath'].strip()
                xmlfile = jsondata['xmlfile'].strip()
                xmlpath = jsondata['xmlpath'].strip()
                cpu = jsondata['cpu'].strip()
                mem = int(jsondata['mem'].strip()) * 1024
                network = jsondata['network'].strip()
                ip_min = jsondata['ip_min'].strip()
                ip_max = jsondata['ip_max'].strip()
                ret = ssh_exec(ipaddr,port,user,password,tempfile,diskpath,xmlfile,xmlpath,cpu,mem,network,ip_min,ip_max,request)
                request.websocket.send(ret)
